//
//  ChatMessageViewController.m
//  jungoo
//
//  Created by Sinbad Flyce on 9/19/12.
//  Copyright (c) 2012 VMODEV. All rights reserved.
//

#import "ChatMessageViewController.h"
#import "Extensions.h"
#import "AlbumController.h"
#import "Photo.h"
#import "OffersViewController.h"
#import "OffersDetailiewController.h"
#import "EventDetailViewController.h"
#import "AsyncImageViewController.h"
#import "ChatMapViewController.h"

#define MT_NORMAL     @"0"
#define MT_BOARDCAST  @"1"
#define MT_LOCATION   @"2"
#define MT_OFFER      @"3"
#define MT_EVENT      @"4"
#define MT_MULTIMEDIA @"5"
#define kPopupHeight 270
@implementation ChatMessageViewController

@synthesize conversionId = _conversionId;
@synthesize lastMessageText = _lastMessageText;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Private

- (void)initAppearance
{
    [self setTitle:@"Message"];

    [self setBackButtonImageActiveName:@""
                          inactiveName:@"back-button"
                                target:self
                                action:@selector(back)];
    
    [self setRightButtonImageActiveName:@""
                           inactiveName:@"edit-button"
                                 target:self
                                 action:@selector(edit)];
    
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg.png"]]];
    [self.tableView setAllowsSelectionDuringEditing:YES];
    
    [JGoUtility showProgressInView:self.view 
                            target:self 
                             title:@"Loading..." 
                          selector:@selector(delayLoadMessages:)];
    
}

- (UITableViewCell*)createLeftCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    
    return (id)[views objectAtIndex:4];
}

- (UITableViewCell*)createRightCellFromNib
{
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MessageView" owner:nil options:nil];
    
    return (id)[views objectAtIndex:3];
}

- (void)tableReload:(NSArray*)messages
{
    if ([messages count] != [dataSource count]) {
        
        [dataSource release];
        dataSource = (id)[messages retain];
        [self.tableView reloadData];
        
        if (lastNumberOfChat != [dataSource count]||
            [dataSource count] == 0) {
        
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataSource count] - 1
                                                                      inSection:0] 
                                  atScrollPosition:UITableViewScrollPositionNone 
                                          animated:YES];                        
            
            lastNumberOfChat = [dataSource count];
        }
    }
}

- (void)asyncLoadAvatars
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        for (NSDictionary *aChat in dataSource) {
            
            NSDictionary *aSender = [aChat objectForKey:@"sender"];                        
            
            if ([aSender isKindOfClass:[NSDictionary class]]) {
                
                NSString *senderAvatarURL = [aSender objectForKey:@"thumb"];
                NSString *senderId = [aSender objectForKey:@"user_id"];
                
                if ([[JGoUtility sharedCachedAvatars] objectForKey:senderId] == nil) {
                    
                    UIImage *senderAvatar = [JGoAPI downloadAvatar:senderAvatarURL error:nil];
                    [[JGoUtility sharedCachedAvatars] setValue:senderAvatar forKey:senderId];
                 }
            }
            
        }
        /*
        [self performSelector:@selector(asyncChatTransation)];
         */
    });    
}

- (void)asyncChatExchange:(NSString*)typeMessage
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        NSDictionary *user = [JGoUtility sharedCreateAccount];
        NSString *userId = [user objectForKey:@"user_id"];
        NSError *error = nil;
        
        BOOL result = [JGoAPI addMessageWithUserId:userId 
                                    conversationId:_conversionId 
                                              type:typeMessage
                                           content:self.lastMessageText
                                             error:&error];
        
        if (result) {
        
        }
        else {
             [JGoUtility showAlert:[error localizedDescription]];
        }
    });    
}

- (void)pushNotification:(NSString*)message
{
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = [NSDate date];
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    
    localNotif.alertBody = message;
    localNotif.alertAction = @"Message";
    
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];
}

/*
- (void)asyncChatTransation
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    
    dispatch_async(queue, ^{
        
        NSDictionary *user = [JGoUtility sharedCreateAccount];
        NSString *userId = [user objectForKey:@"user_id"];
        
        while (1) {
    
            NSError *error = nil;        
            NSArray *messages = [JGoAPI getMessagesWithUserId:userId 
                                               conversationId:_conversionId 
                                                     fromDate:@"" 
                                                       toDate:@"" error:&error];
            if (!error) {
                [dataSource release];
                dataSource = nil;
                dataSource = (id)[[messages reverseObjectEnumerator] allObjects];
                [dataSource retain];
                [self performSelectorOnMainThread:@selector(tableReload) withObject:nil waitUntilDone:YES];
            }
            
            sleep(5);
            
        }
    });
}
 */


- (NSString*)contentForChat:(NSDictionary*)aChat
{
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_NORMAL]) {
        return [aChat objectForKey:@"content"];
    }
    
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_EVENT]) {
        
        NSArray *arrayString = [[aChat objectForKey:@"content"] componentsSeparatedByString:@" - "];
        
        if ([arrayString count] > 1) {
            return [NSString stringWithFormat:@"[Event] %@",[arrayString objectAtIndex:1]];
        }
        
        return [aChat objectForKey:@"content"];
    }

    if ([[aChat objectForKey:@"type"] isEqualToString:MT_OFFER]) {
        
        NSArray *arrayString = [[aChat objectForKey:@"content"] componentsSeparatedByString:@" - "];
        
        if ([arrayString count] > 1) {
            return [NSString stringWithFormat:@"[Offer] %@",[arrayString objectAtIndex:1]];
        }
        
        return [aChat objectForKey:@"content"];
    }
    
    return [aChat objectForKey:@"content"];
}

- (void)selectedChat:(NSDictionary*)aChat
{
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_NORMAL]) {
        return ;
    }
    
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_LOCATION]) {
        
        ChatMapViewController *chatMapVC = [[[ChatMapViewController alloc] initWithNibName:@"ChatMapViewController" bundle:nil] autorelease];
        chatMapVC.latLonString = [aChat objectForKey:@"content"];
        [self.navigationController pushViewController:chatMapVC animated:YES];
        
        return ;
    }
    
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_EVENT]) {
        
        EventDetailViewController *eventDetailVC = [[[EventDetailViewController alloc] initWithNibName:@"EventDetailViewController" bundle:nil] autorelease];
        
        NSArray *arrayString = [[aChat objectForKey:@"content"] componentsSeparatedByString:@" - "];
        
        if ([arrayString count] > 1) {
            NSString *eventId = [arrayString objectAtIndex:0];
            [eventDetailVC setEventId:eventId];
            [self.navigationController pushViewController:eventDetailVC animated:YES];
        }        
        
        return;
    }
    
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_OFFER]) {
        
        OffersDetailiewController *offerDetailVC = [[[OffersDetailiewController alloc] initWithNibName:@"OffersDetailiewController" bundle:nil] autorelease];        
        
        NSArray *arrayString = [[aChat objectForKey:@"content"] componentsSeparatedByString:@" - "];
        
        if ([arrayString count] > 1) {
            NSString *offerId = [arrayString objectAtIndex:0];
            [offerDetailVC setOfferId:offerId];
            [self.navigationController pushViewController:offerDetailVC animated:YES];            
        }

        return;
    }
      
    if ([[aChat objectForKey:@"type"] isEqualToString:MT_MULTIMEDIA]) {
        AsyncImageViewController *asyncImageVC = [[[AsyncImageViewController alloc] initWithNibName:@"AsyncImageViewController" bundle:nil] autorelease];
        
        [asyncImageVC setUrlString:[aChat objectForKey:@"content"]];
        [self.navigationController pushViewController:asyncImageVC animated:YES];        
    }
}

- (UIButton*)recheckUIFromCell:(UITableViewCell*)cell recheck:(BOOL)check
{
    UIButton *recheckTmp = (id)[cell.contentView viewWithTag:0x100];
    
    if (recheckTmp == nil) {
        recheckTmp = [UIButton buttonWithType:UIButtonTypeCustom];
    }
    
    [recheckTmp setBackgroundImage:[UIImage imageNamed:check ? @"message-check.png": @"message-uncheck.png"]
                          forState:UIControlStateNormal];
    [recheckTmp addTarget:self action:@selector(recheck:) forControlEvents:UIControlEventTouchUpInside];
    [recheckTmp setFrame:CGRectMake(-27, 22, 27, 27)];
    [recheckTmp setTag:0x100];
    
    return recheckTmp;
}

- (void)changeModeEdit:(BOOL)edit
{
    if (edit) {
        [enterChatView removeFromSuperview];
        [clearUIView setFrame:CGRectMake(0, 372, 320, 44)];
        [clearButton setTitle:[NSString stringWithFormat:@"Clear all (%d)",[dataSource count]]
                     forState:UIControlStateNormal];
        [self.view addSubview:clearUIView];
        [self setBackButtonImageActiveName:@""
                              inactiveName:@"cancel-button"
                                    target:self
                                    action:@selector(cancel)];
        
        [self setRightButtonImageActiveName:@""
                               inactiveName:@"delete-button"
                                     target:self
                                     action:@selector(edit)];
        
    }
    else {
        [clearUIView removeFromSuperview];
        [enterChatView setFrame:CGRectMake(0, 372, 320, 44)];
        [self.view addSubview:enterChatView];
        
        [self setBackButtonImageActiveName:@""
                              inactiveName:@"back-button"
                                    target:self
                                    action:@selector(back)];
        
        [self setRightButtonImageActiveName:@""
                               inactiveName:@"edit-button"
                                     target:self
                                     action:@selector(edit)];
    }
    
    [self.tableView reloadData];
}

#pragma mark - Action

- (void)edit
{
    if (self.tableView.editing) {
        
        NSInteger count = 0;
        
        for (NSDictionary *aMessage in dataSource) {
            
            if ([[aMessage objectForKey:@"check"] integerValue] == 1) {
                count++;
            }
        }
        
        if (count == 0) {
            [JGoUtility showAlert:@"Please select one or more items to remove"];
            return;
        }
        
        [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                target:self
                                 title:@"Deleting..."
                              selector:@selector(delayDelete:)];
    }
    else {
        self.tableView.editing = YES;
        [self changeModeEdit:self.tableView.editing];
        [self.tableView reloadData];
    }
}

- (void)back
{
    if ([self.navigationController.viewControllers count] > 1) {
        [[MessageNotifyCenter sharedMessageNotify] setDelegate:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [[MessageNotifyCenter sharedMessageNotify] setDelegate:nil];
        [self dismissModalViewControllerAnimated:YES];
    }
}

- (void)cancel
{
    self.tableView.editing = NO;
    
    [self setRightButtonImageActiveName:@""
                           inactiveName:@"edit-button"
                                 target:self
                                 action:@selector(edit)];
    [self setBackButtonImageActiveName:@""
                          inactiveName:@"back-button"
                                target:self
                                action:@selector(back)];
    
    [self changeModeEdit:NO];
    [self.tableView reloadData];
}

- (IBAction)senderMessage:(id)sender
{
    UITextField *enterChatText = (id)[enterChatView viewWithTag:1];
    
    if ([enterChatText.text length]) {
        [self setLastMessageText:enterChatText.text];
        [self asyncChatExchange:MT_NORMAL];
        [enterChatText setText:@""];
    }
}

- (IBAction)share:(id)sender
{
    if (uiasView == nil)
    {
        NSArray *buttonArr = [NSArray arrayWithObjects:@"Photo",@"Share location",@"Share deal",@"Share event", nil];
        self.uiasView = [[CustomUIASView alloc] initWithFrameAndSource:CGRectMake(0, (self.view.frame.size.height + kPopupHeight), 320, kPopupHeight) buttonTitles:buttonArr moreThreeButton:YES];
        
        [self.uiasView.firstButton addTarget:self action:@selector(sharePhoto) forControlEvents:UIControlEventTouchUpInside];
        [self.uiasView.secondButton addTarget:self action:@selector(shareLocation) forControlEvents:UIControlEventTouchUpInside];
        [self.uiasView.thirdButton addTarget:self action:@selector(shareDeal) forControlEvents:UIControlEventTouchUpInside];
        [self.uiasView.fourthButton addTarget:self action:@selector(shareEvent) forControlEvents:UIControlEventTouchUpInside];
        [self.uiasView.cancelButton addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.uiasView];
    }
   
    [self presentView];
    /*
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Share"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"Photo",@"Deal",@"Location",@"Event", nil];
    [sheet showInView:self.view];
    [sheet release];
     */
}

- (IBAction)deleteMessages:(id)sender
{
    [[[[UIAlertView alloc] initWithTitle: @"Alumnee"
								 message: @"Are you sure to want remove all items?"
								delegate: (id)self
					   cancelButtonTitle: @"Yes"
					   otherButtonTitles: @"No",nil] autorelease] show];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initAppearance];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MessageNotifyCenter sharedMessageNotify].delegate = self;
}

-(void) dealloc
{
    [uiasView release];
    [MessageNotifyCenter sharedMessageNotify].delegate = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataSource count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = nil;
    NSDictionary *aChat = [dataSource objectAtIndex:indexPath.row];
    NSDictionary *sender = [aChat objectForKey:@"sender"];
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    
    if ([sender isKindOfClass:[NSDictionary class]]) {
        sender = [aChat objectForKey:@"sender"];
    }
    
    NSString *senderId = [sender objectForKey:@"user_id"];
    NSDate *dateChat = [JGoUtility dateFromString3:[aChat objectForKey:@"created_time"]];
    
    if ([userId isEqualToString:senderId]) {
        cell = [self createRightCellFromNib];
        [cell imageViewWithTag:6].hidden = NO;
    }
    else {
        cell = [self createLeftCellFromNib];
        [cell imageViewWithTag:6].hidden = YES;
    }    
    
    if (tableView.editing) {
        BOOL check = ([[aChat objectForKey:@"check"] integerValue] == 1);
        [cell.contentView addSubview:[self recheckUIFromCell:cell recheck:check]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    else {
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    }
    
    [cell imageViewWithTag:1].image = [[JGoUtility sharedCachedAvatars] objectForKey:senderId];
    [cell titleTextWithTag:2].text = [sender objectForKey:@"name"];
    [cell titleTextWithTag:4].text = [self contentForChat:aChat];
    [cell titleTextWithTag:3].text = [JGoUtility stringFromDate5:dateChat];   
    [[cell imageViewWithTag:1] makeBorderRound];    
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
     
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 72;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *aView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)] autorelease];
    aView.backgroundColor = [UIColor clearColor];
    
    return aView;    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView.editing) {
        NSDictionary *aChat = [dataSource objectAtIndex:indexPath.row];
        NSInteger check = [[aChat objectForKey:@"check"] integerValue];
        check = !check;
        [aChat setValue:[NSString stringWithFormat:@"%d",check] forKey:@"check"];
        [self.tableView reloadData];
    }
    else {
        NSDictionary *aChat = [dataSource objectAtIndex:indexPath.row];
        [self selectedChat:aChat];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}


#pragma mark - Delay Method

- (void)delayLoadMessages:(MBProgressHUD*)progress
{
    NSDictionary *user = [JGoUtility sharedCreateAccount];
    NSString *userId = [user objectForKey:@"user_id"];
    NSError *error = nil;
    
    listImages = (id)[JGoAPI getPhotoWithUserId:userId error:&error];
    
    if ([listImages count]) {
        [listImages retain];
    }
    else {
        listImages = nil;
    }
    
    error = nil;
    
    NSArray *messages = [JGoAPI getMessagesWithUserId:userId
                                       conversationId:_conversionId 
                                             fromDate:@"" 
                                               toDate:@"" error:&error];
    
    
    if (!error) {
        
        if ([messages count]) {
            dataSource = (id)[[messages reverseObjectEnumerator] allObjects];
            [dataSource retain];        
            [self.tableView reloadData];
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataSource count] - 1
                                                                      inSection:0] 
                                  atScrollPosition:UITableViewScrollPositionNone 
                                          animated:YES];
            [self asyncLoadAvatars];        
            
            lastNumberOfChat = [dataSource count];
        }
    }
    else {
        [JGoUtility showAlert:[error localizedDescription]];
    }
    
    [progress hide:YES];
    
}

- (void)delayDelete:(MBProgressHUD*)progress
{
    /*
     NSDictionary *user = [JGoUtility sharedCreateAccount];
     NSString *userId = [user objectForKey:@"user_id"];
     */
    
    NSError *error = nil;
    NSMutableArray *mids = [[NSMutableArray new] autorelease];
    
    for (NSDictionary *aMessage in dataSource) {
        
        if ([[aMessage objectForKey:@"check"] integerValue] == 1) {
            [mids addObject:[aMessage objectForKey:@"id"]];
        }
    }
    
    if ([mids count]) {
        BOOL result = [JGoAPI deleteMessagesWithMessageIds:[mids componentsJoinedByString:@";"] error:&error];
        
        if (result) {
            
            NSMutableArray *willRemoveItems = [[NSMutableArray new] autorelease];
            
            for (int iMes = 0; iMes < [dataSource count]; iMes++) {
                
                NSDictionary *aMessage = [dataSource objectAtIndex:iMes];
                
                if ([[aMessage objectForKey:@"check"] integerValue] == 1) {
                    [willRemoveItems addObject:aMessage];
                }
            }
            
            for (NSDictionary *aMessage in willRemoveItems) {
                [dataSource removeObject:aMessage];
            }
            
            self.tableView.editing = NO;
            [self changeModeEdit:self.tableView.editing];
            [self.tableView reloadData];
        }
        else {
            [JGoUtility showAlert:[error localizedDescription]];
        }
    }
    
    [progress hide:YES];
}

- (void)delayDeleteAll:(MBProgressHUD*)progress
{
    /*
     NSDictionary *user = [JGoUtility sharedCreateAccount];
     NSString *userId = [user objectForKey:@"user_id"];
     */
    
    NSError *error = nil;
    NSMutableArray *mids = [[NSMutableArray new] autorelease];
    
    for (NSDictionary *aMessage in dataSource) {
        [mids addObject:[aMessage objectForKey:@"id"]];
    }
    
    if ([mids count]) {
        BOOL result = [JGoAPI deleteMessagesWithMessageIds:[mids componentsJoinedByString:@";"] error:&error];
        
        if (result) {
            
            [dataSource release];
            dataSource = nil;
            
            self.tableView.editing = NO;
            [self changeModeEdit:self.tableView.editing];
            [self.tableView reloadData];
        }
        else {
            [JGoUtility showAlert:[error localizedDescription]];
        }
    }
    
    [progress hide:YES];
}

#pragma mark - TextField Delegeate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:nil context:NULL];    
    CGRect newRect = CGRectMake(0, 200 - 44, 320, 44);
    enterChatView.frame = newRect;
    [UIView commitAnimations];
    
    if ([dataSource count]) {
        [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 218, 0)];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataSource count] - 1
                                                                  inSection:0] 
                              atScrollPosition:UITableViewScrollPositionNone 
                                                                   animated:YES];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    CGRect newRect = CGRectMake(0, 372, 320, 44);
    enterChatView.frame = newRect;

    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    return YES;
}

#pragma mark - Sheet Delegate

- (void)presentView
{
    
    [UIView animateWithDuration:0.60f animations:^{
        
        CGRect uiasViewFrame   = self.uiasView.frame;
        uiasViewFrame.origin.y = (self.view.frame.size.height - kPopupHeight);
        
        self.uiasView.frame = uiasViewFrame;
    }];
    
    //self.presentASButton.enabled = NO;
}
- (void)dismissView {
    
    [UIView animateWithDuration:0.75f animations:^{
        
        CGRect uiasViewFrame   = self.uiasView.frame;
        uiasViewFrame.origin.y = (self.view.frame.size.height + kPopupHeight);
        
        self.uiasView.frame = uiasViewFrame;
    }];
    
    //self.presentASButton.enabled = YES;
}
-(void)sharePhoto
{
    [self dismissView];
    albumViewController.navController = self.navigationController;
    albumViewController.photos = nil;
    albumViewController.type = AlbumForShare;
    albumViewController.ownerDelegate = self;
    albumViewController.photos = listImages;
    [self.navigationController pushViewController:albumViewController animated:YES];
}
-(void)shareLocation
{
    [self dismissView];
    NSString *myLocation =  [NSString stringWithFormat:@"%@;%@",[JGoUtility sharedLatitude],[JGoUtility sharedLongitude]];
    [self setLastMessageText:myLocation];
    [self asyncChatExchange:MT_LOCATION];
        
}

-(void)shareDeal
{
    [self dismissView];
    OffersViewController *offerVC = [[[OffersViewController alloc] initWithNibName:@"OffersViewController" bundle:nil] autorelease];
    offerVC.mode = OfferForShare;
    offerVC.delegate = self;
    [self.navigationController pushViewController:offerVC animated:YES];
}

-(void)shareEvent
{
    [self dismissView];
    EventViewController *eventVC = [[[EventViewController alloc] initWithNibName:@"EventViewController" bundle:nil] autorelease];
    eventVC.mode = EventForShare;
    eventVC.delegate = self;
    [self.navigationController pushViewController:eventVC animated:YES];
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0: {
            albumViewController.navController = self.navigationController;
            albumViewController.photos = nil;
            albumViewController.type = AlbumForShare;
            albumViewController.ownerDelegate = self;
            albumViewController.photos = listImages;
            [self.navigationController pushViewController:albumViewController animated:YES];
            break;
        }
        case 1: {
            OffersViewController *offerVC = [[[OffersViewController alloc] initWithNibName:@"OffersViewController" bundle:nil] autorelease];
            offerVC.mode = OfferForShare;
            offerVC.delegate = self;
            [self.navigationController pushViewController:offerVC animated:YES];
            break;
        }
        case 2: {
            NSString *myLocation =  [NSString stringWithFormat:@"%@;%@",[JGoUtility sharedLatitude],[JGoUtility sharedLongitude]];
            [self setLastMessageText:myLocation];
            [self asyncChatExchange:MT_LOCATION];
            break;
        }
        case 3: {
            EventViewController *eventVC = [[[EventViewController alloc] initWithNibName:@"EventViewController" bundle:nil] autorelease];
            eventVC.mode = EventForShare;
            eventVC.delegate = self;
            [self.navigationController pushViewController:eventVC animated:YES];
            break;
        }
        case 4: {
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - Share Delegate

- (void)albumController:(AlbumController*)albumVC didSelectWithURL:(NSString*)selectedURL
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [self setLastMessageText:selectedURL];
    [self asyncChatExchange:MT_MULTIMEDIA];
    
    [albumVC.navigationController popViewControllerAnimated:YES];
}

- (void)eventViewController:(EventViewController *)controller didSelectedWithEvent:(NSDictionary *)aEvent
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [self setLastMessageText:[NSString stringWithFormat:@"%@ - %@",[aEvent objectForKey:@"event_id"],[aEvent objectForKey:@"event_title"]]];
    [self asyncChatExchange:MT_EVENT];
    
    [controller.navigationController popViewControllerAnimated:YES];
}

- (void)offersViewController:(OffersViewController *)controller didSelectedWithOffer:(NSDictionary *)offer
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [self setLastMessageText:[NSString stringWithFormat:@"%@ - %@",[offer objectForKey:@"id"],[offer objectForKey:@"title"]]];
    [self asyncChatExchange:MT_OFFER];
    
    [controller.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Message Center 

- (NSString*)activeIdentifier
{
    return _conversionId;
}

- (void)messageNotifyCenter:(MessageNotifyCenter *)centerNotify lastMessages:(NSArray *)messages
{
    if (!self.tableView.editing) {
        [self performSelectorOnMainThread:@selector(tableReload:) withObject:messages waitUntilDone:YES];
    }
}

#pragma mark - UIAlertDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                                target:self title:@"Deleting..."
                              selector:@selector(delayDeleteAll:)];
    }
}

@end
